package com.unohacha.qqj.fzdr.main;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppExpressBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppExpressLBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeExpressHistoryBean;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.personal.view.activity.KuaidiCompanyActivity;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 快递查询
 */
public class ExpressLookActivity extends BaseActivity {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.express_no)
    EditText expressNo;
    @BindView(R.id.wl_company)
    TextView wlCompany;
    @BindView(R.id.tv_look)
    TextView tvLook;
    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;
    @BindView(R.id.clear_search_h)
    TextView clearSearchH;
    @BindView(R.id.express_ll)
    LinearLayout express_ll;
    @BindView(R.id.scanf_iv)
    ImageView scanf_iv;

    private List<HomeAppExpressLBean.DataBean> mAppExpressList = new ArrayList<>();//快递公司的集合
    private int expressId;//选中的快递公司的id
    private String expressName;//选中的快递公司的名字
    private List<HomeAppExpressBean.DataBeanX.DataBean> mExpressInfoList = new ArrayList<>();//物流信息集合
    private HomeAppExpressBean.DataBeanX mExpressData;
    private BaseRVAdapter mExpressAdapter;
    private List<HomeExpressHistoryBean.DataBean> mHistoryList = new ArrayList<>();
    ;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_express_look;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText(getResources().getString(R.string.express_look));
        commonRightText.setVisibility(View.VISIBLE);
        commonRightText.setText(getResources().getString(R.string.express_company));
        commonRightImage.setVisibility(View.GONE);
        carListRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        carListRecycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        lookHistory();
    }

    @OnClick({R.id.common_back, R.id.clear_search_h, R.id.tv_look,
            R.id.express_ll, R.id.scanf_iv, R.id.common_right_text})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.tv_look://查询
                if (TextUtils.isEmpty(expressNo.getText().toString().trim())) {
                    MyToast("请输入物流单号!");
                    return;
                }

                if (TextUtils.isEmpty(wlCompany.getText().toString().trim())) {
                    MyToast("请输入物流公司!");
                    return;
                }

                lookByExpressNo(expressName, expressNo.getText().toString().trim());
                break;

            case R.id.scanf_iv://扫描
                //调用zxing
                IntentIntegrator intentIntegrator = new IntentIntegrator(ExpressLookActivity.this);
                intentIntegrator
                        .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
                        .setPrompt("将二维码/条码放入框内，即可自动扫描")//写那句提示的话
                        .setOrientationLocked(false)//扫描方向固定
                        .setCaptureActivity(CustomScanActivity.class) // 设置自定义的activity是CustomActivity
                        .initiateScan(); // 初始化扫描
                break;
            case R.id.express_ll://物流公司选择 弹出选择框
                chooseExpress("");
                break;
            case R.id.clear_search_h://清空搜索历史
                deleteRecode(2, "");
                break;
            case R.id.common_right_text://快递公司
                Intent intent = new Intent(this, KuaidiCompanyActivity.class);
                startActivity(intent);
                break;
        }
    }


    //选择快递公司
    private void chooseExpress(String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("keyword", keyword);
        XUtil.Post(UrlConfig.EXPRESS_COMPANY, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeAppExpressLBean expressLBean = gson.fromJson(result, HomeAppExpressLBean.class);
                        if (null != expressLBean) {
                            if (null != mAppExpressList) {
                                mAppExpressList.clear();
                            }

                            mAppExpressList.addAll(expressLBean.getData());
                            showIndustryPickciew();
                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    /**
     * 快递公司选择器
     */
    private void showIndustryPickciew() {
        if (mAppExpressList.size() == 0) {
            MyToast("暂无可选项目");
            return;
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < mAppExpressList.size(); i++) {
            list.add(mAppExpressList.get(i).getName());
        }
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                expressId = mAppExpressList.get(options1).getId();
                expressName = mAppExpressList.get(options1).getExpress_ma();
                wlCompany.setText(mAppExpressList.get(options1).getName());
            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.green1ccf70))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.green1ccf70))//取消按钮文字颜色.build();
                .setCyclic(false, false, false)
                .build();
        pvOptions.setPicker(list);//一级选择器
        pvOptions.show();
    }


    //通过快递单号查询快递信息 
    private void lookByExpressNo(String express_ma, String express_no) {
        showLoading();
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("express_ma", express_ma);
        params.put("express_no", express_no);
        XUtil.Post(UrlConfig.APP_EXPRESS, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeAppExpressBean expressBean = gson.fromJson(result, HomeAppExpressBean.class);
                        if (null != expressBean) {
                            if (null != mExpressInfoList) {
                                mExpressInfoList.clear();
                            }

                            mExpressData = expressBean.getData();
                            mExpressInfoList.addAll(expressBean.getData().getData());
                            if (null != mExpressData) {
                                Intent intent = new Intent(ExpressLookActivity.this, ExpressCheckActivity.class);
                                intent.putExtra("data", mExpressData);
                                startActivity(intent);
                            }

                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                        ToastUtils.showT(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ToastUtils.showT("onError");
            }
        });
        hideLoading();
    }


    //查看历史记录
    private void lookHistory() {
        showLoading();
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        XUtil.Post(UrlConfig.APP_EXPRESS_QUERY, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeExpressHistoryBean historyBean = gson.fromJson(result, HomeExpressHistoryBean.class);

                        if (null != historyBean) {
                            if (null != mHistoryList) {
                                mHistoryList.clear();
                            }
                            mHistoryList.addAll(historyBean.getData());
                            setExpressAdapter();
                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                hideLoading();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Log.e("TAG2", ex.toString());
            }
        });
    }

    //设置快递数据
    private void setExpressAdapter() {
        mExpressAdapter = new BaseRVAdapter(this, mHistoryList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_express_look;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                TextView express_name_no = holder.getTextView(R.id.express_name_no);
                ImageView clear_tv = holder.getImageView(R.id.clear_tv);

                if (null != mHistoryList) {
                    express_name_no.setText(mHistoryList.get(position).getCourier_company());
                    clear_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {//删除单条
                            ToastUtils.showT("删除单条");
                            deleteRecode(1, mHistoryList.get(position).getId() + "");
                        }
                    });
                }
            }
        };

        carListRecycler.setAdapter(mExpressAdapter);
        mExpressAdapter.notifyDataSetChanged();
    }

    //删除历史记录
    private void deleteRecode(int type, String id) {
        showLoading();
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("type", type);
        if (type == 1) {
            params.put("id", id);
        }
        XUtil.Post(UrlConfig.APP_EXPRESS_QUERY_DEL, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG:deleteRecode", result.toString());
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    MyToast(jsonObject.optString("message"));
                    if (1 == jsonObject.optInt("code")) {
                        lookHistory();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                super.onFinished();
                hideLoading();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                hideLoading();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        lookHistory();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null && null != intentResult.getContents()) {
            String scanResult = intentResult.getContents();
            expressNo.setText(scanResult);
            Log.e("TAG: 扫描结果: ", scanResult);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
